# -*- coding: utf-8 -*-
import sys
if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')
#from xbmcswift2_patched import plugin, log, sto, _, message, show_plugin_dir, add_nav_item, show_plugin_path, menu_item_goto, run_plugin_item, expandItemsFromContextMenu, get_page_nav_items, add_page_nav_items
import xbmcswift2_patched as xbmcswift2
from xbmcswift2_patched import xbmc, xbmcaddon, xbmcgui, plugin, log, _, message, get_downloader
import lockfile
from pprint import pprint
import os, time, shutil, threading, urllib2, re
#try:
#    import StorageServer
#except:
#    import storageserverdummy as StorageServer
#cache = StorageServer.StorageServer("dmdsplayer", 24) # (Your plugin name, Cache time in hours)
#cache.dbg = True
#cache.dbglevel = 5

ADDON_ID = 'plugin.program.dmdsplayer'

DEFAULT_CLIENTID = 'DMDS-XBC-XXXX'

if xbmcswift2.CLI_MODE:
    addon_icon_path = './icon.png'
    plugin.set_setting('playdir', '')
    plugin.set_setting('clientid', 'DMDS-XBC-0001')
    plugin.set_setting('guinotify', 'true')
    plugin.set_setting('runonstartup', 'false')
    plugin.set_setting('check_update_interval', '0')
    plugin.set_setting('schedule_poweroff', 'true')
    plugin.set_setting('schedule_poweroff_hour', '18')
    plugin.set_setting('schedule_poweroff_min', '0')
    plugin.set_setting('sync_screenshot', 'true')
else:
    addon_icon_path = xbmc.translatePath(os.path.join(plugin.addon.getAddonInfo('path'), 'icon.png'))

#playdir = plugin.get_setting('playdir')
clientid = plugin.get_setting('clientid', str, '')
nogui = not plugin.get_setting('guinotify', bool, True)
runonstartup = plugin.get_setting('runonstartup', bool, False)

log.debug('nogui: %s' % nogui)

def notify(msg, nogui = nogui):
    if nogui:
        log.info(msg)
    else:
        plugin.notify(msg)

def get_external_ip():
    try:
        site = urllib2.urlopen("http://checkip.dyndns.org/").read()
        grab = re.findall('\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3}', site)
        address = grab[0]
        return address
    except:
        return 'unknown'

def get_screenshot_dir():
    return xbmc.translatePath('special://screenshots/')

def get_package_filename():
    if clientid != DEFAULT_CLIENTID:
        return '%s.zip' % clientid

def get_package_url():
    pkg_file = get_package_filename()
    if pkg_file:
        return 'http://31.192.228.186/media_files/%s' % pkg_file

DATA_BASE_DIR = xbmc.translatePath('special://profile/addon_data/%s/' % ADDON_ID)

def get_plugin_dir(doTranslate=True):
    path = 'special://home/addons/%s/' % ADDON_ID
    if doTranslate:
        path = xbmc.translatePath(path)
    return path

def get_plugin_resource_dir():
    return xbmc.translatePath('special://home/addons/%s/resources/' % ADDON_ID)

def get_plugin_media_dir():
    return xbmc.translatePath('special://home/addons/%s/resources/media/' % ADDON_ID)

def get_default_screenshot_file():
    return os.path.join(get_plugin_media_dir(), 'dummy_screenshot.png')

def get_mvg_logo(doTranslate=True):
    return os.path.join(get_plugin_dir(doTranslate), 'fanart.jpg')

def get_package_file():
    pkg_file = get_package_filename()
    if pkg_file:
        return os.path.join(DATA_BASE_DIR, pkg_file)

def get_default_playdir():
    global plugin
    playdir = os.path.join(DATA_BASE_DIR, 'PlayDir')
    return playdir

def get_playdir():
#    playdir = plugin.get_setting('playdir', str)
#    if not playdir:
    playdir = get_default_playdir()
    if not os.path.isdir(playdir):
        os.makedirs(playdir)
    return os.path.join(os.path.dirname(playdir), os.path.basename(playdir))

def get_password():
    return 'password'

def set_zip_file_timestamps(z, rootdir):
    dirs = []
    for info in z.infolist():
        if info.filename[-1] != '/':
            lm = time.mktime(tuple(list(info.date_time) + [0, 0, 0]))
            try:
                os.utime(os.path.join(rootdir, info.filename), (lm, lm))
            except OSError, e:
                pass
        else:
            dirs.append((info.filename.count('/'), info))
    dirs.sort()
    dirs.reverse()
    for depth, info in dirs:
        lm = time.mktime(tuple(list(info.date_time) + [0, 0, 0]))
        try:
            os.utime(os.path.join(rootdir, info.filename), (lm, lm))
        except OSError, e:
            pass

@plugin.route('/extract_media_files')
def extract_media_files(nogui = nogui):
    def notify(msg, nogui = nogui):
        if nogui:
            log.info(msg)
        else:
            plugin.notify(msg)

    pkg_file = get_package_file()
    if not os.path.isfile(pkg_file):
        log.error('pkg file not exists: %s' % pkg_file)
        notify('media file package does not exist.')
        return
    playdir = get_playdir()
    playdirnew = playdir + '.new'
    if not os.path.isdir(playdirnew):
        os.makedirs(playdirnew)
    try:
        import zipfile
        z = zipfile.ZipFile(open(pkg_file, 'rb'))
        notify('extracting media content...')
        shutil.rmtree(playdirnew, True)
        #z.extractall(playdirnew, pwd=get_password())
        z.extractall(playdirnew)
        set_zip_file_timestamps(z, playdirnew)
    except:
        shutil.rmtree(playdirnew, True)
        raise
    notify('media files extracted, moving...')

    playdirold = playdir + '.old'
    shutil.rmtree(playdirold, True)
    os.rename(playdir, playdirold)
    os.rename(playdirnew, playdir)
    log.debug('media files extracted to %s' % playdir)
    notify('media files updated.')
    
def notify(msg, nogui = nogui):
    if nogui:
        log.info(msg)
    else:
        plugin.notify(msg)

def lock_and_call_else_fail(lockname):
    def wrap(f):
        def wrapped_f(*args):
            try:
                log.debug('locking [%s]' % lockname)
                lock = lockfile.LockFile(os.path.join(DATA_BASE_DIR, lockname))
                if lock.is_locked():
                    notify('lock [%s] failed.' % lockname)
                    return
                lock.acquire()
                log.debug('[%s] locked' % lockname)
            except lockfile.Error, e:
                notify('lock [%s] failed: %s' % (lockname, e))
                return
            except:
                notify('lock [%s] exception.' % lockname)
            try:
                return f(*args)
            finally:
                try:
                    log.debug('unlocking [%s]' % lockname)
                    lock.release()
                    log.debug('[%s] unlocked' % lockname)
                except lockfile.Error, e:
                    notify('unlock [%s] failed: %s' % (lockname, e))
                except:
                    notify('unlock [%s] exception.' % lockname)
        return wrapped_f
    return wrap

def does_skin_support_set_background(skin_name=None):
    if skin_name is None:
        skin_name = xbmc.getSkinDir()
    return skin_name in ['skin.confluence']

def does_skin_background_set_to_mvg_logo():
    if not does_skin_support_set_background():
        return False
    if not xbmc.getCondVisibility("Skin.HasSetting(UseCustomBackground)"):
        return False
    mvg_logo_path = get_mvg_logo(False)
    return xbmc.getInfoLabel('Skin.String(CustomBackgroundPath)') == mvg_logo_path

@plugin.route('/set_skin_background')
def set_skin_background():
    #skin_name = xbmc.getInfoLabel('Skin.CurrentTheme')
    skin_name = xbmc.getSkinDir()
    if does_skin_support_set_background(skin_name):
        xbmc.executebuiltin("Skin.SetBool(UseCustomBackground)", True)
        mvg_logo_path = get_mvg_logo(False)
        xbmc.executebuiltin("Skin.SetString(CustomBackgroundPath,%s)" % mvg_logo_path, True)
        notify('MVG logo now set to background.')
    else:
        notify('Unsupported skin: %s' % skin_name)

def check_ask_set_skin_background():
    if plugin.get_setting('ask_set_logo_to_bg', bool, True):
        if not does_skin_background_set_to_mvg_logo():
            # ask
            dialog = xbmcgui.Dialog()
            confirmed = dialog.yesno(plugin.name, _('Do you want to set MVG DMDS Logo to XBMC background?'))
            if confirmed:
                set_skin_background()
        plugin.set_setting('ask_set_logo_to_bg', 'false')


@plugin.route('/cleanup_media_files')
def cleanup_media_files():
    pkg_file = get_package_file()
    if os.path.exists(pkg_file):
        os.remove(pkg_file)
        notify('media package deleted.')
    playdir = get_playdir()
    if os.path.isdir(playdir):
        shutil.rmtree(playdir, True)
        notify('playdir deleted.')
    notify('cleanup finished.')

@plugin.route('/check_media_updates')
def check_media_updates():
    check_media_updates_nolock()

@lock_and_call_else_fail('check_update')
def check_media_updates_nolock(nogui = nogui):
    def notify(msg, nogui = nogui):
        if nogui:
            log.info(msg)
        else:
            plugin.notify(msg)

    url = get_package_url()
    if not url:
        notify('invalid client id')
        return
    pkg_file = get_package_file()
    if os.path.exists(pkg_file):
        mtime = os.path.getmtime(pkg_file)
        url += '|If-Modified-Since=%s' % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(mtime))
    opts = { "url": url, "download_path": DATA_BASE_DIR, "Title": '%s - Checking media updates' % plugin.name}
    opts['nogui'] = nogui

    pprint(opts)
    downloader = get_downloader()
    try:
        ret = downloader.download(get_package_filename(), opts)
    except urllib2.HTTPError, e:
        log.error('[%s] http error: %s' % (url, e))
        if e.code == 404:
            notify('no media package match client id.')
            return
        ret = 'false'
    except:
        if not xbmc.getCondVisibility("System.InternetState"):
            notify('internet not available, can not check dmds media update.');
            return
        else:
            raise
    log.info("downloader ret: %s" % ret)

    if ret == 'not modified':
        notify('no media update.')
    elif ret == 'canceled':
        pass
    elif ret == 'false':
        notify('media update failed.')
    elif ret == 'downloaded':
        notify('media update downloaded.')
        extract_media_files(nogui)

def get_traceback():
    from cStringIO import StringIO
    h = StringIO()
    import traceback
    traceback.print_exc(file=h)
    return h.getvalue()

def generate_report():
    """template = '''<?xml version="1.0" ?>
<dmdssurveillance>
  <clientname>{clientname}</clientname>
  <wanip>{wanip}</wanip>
  <localip>{localip}</localip>
  <uptimenormal>{uptimenormal}</uptimenormal>
  <uptimeminutes>{uptimeminutes}</uptimeminutes>
  <alivekey>{alivekey}</alivekey>
  <lastreboot>{lastreboot}</lastreboot>
  <lastupdatekey>SWARM Server Updated Client at: {lastupdatekey}</lastupdatekey>
  <certificate>{certificate}</certificate>
</dmdssurveillance>
'''"""
    try:
        import subprocess
        if not hasattr(subprocess, 'check_output'):
            def check_output(*popenargs, **kwargs):
                r"""Run command with arguments and return its output as a byte string.
 
                Backported from Python 2.7 as it's implemented as pure python on stdlib.
 
                >>> check_output(['/usr/bin/python', '--version'])
                Python 2.6.2
                """
                process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
                output, unused_err = process.communicate()
                retcode = process.poll()
                if retcode:
                    cmd = kwargs.get("args")
                    if cmd is None:
                        cmd = popenargs[0]
                    error = subprocess.CalledProcessError(retcode, cmd)
                    error.output = output
                    raise error
                return output
            subprocess.check_output = check_output

        import uptime
        ut = uptime.uptime()
        def get_duration_str(secs):
            import datetime
            td = datetime.timedelta(seconds = secs)
            rets = []
            if td.days:
                ret = '%d day' % td.days
                if td.days > 1:
                    ret += 's'
                rets.append(ret)
            h = int(td.seconds/3600)
            if h:
                ret = '%d hour' % h
                if h > 1:
                    ret += 's'
                rets.append(ret)
            m = int(td.seconds%3600/60)
            if m:
                ret = '%d minute' % m
                if m > 1:
                    ret += 's'
                rets.append(ret)
            return ' '.join(rets)

        utstr = get_duration_str(ut)
        try:
            utcmdret = subprocess.check_output('uptime').strip()
        except:
            utcmdret = ''
        opts = {
            'clientname': clientid,
            'wanip': get_external_ip(),
            'localip': xbmc.getInfoLabel('Network.IPAddress'),
            'uptimenormal': utcmdret,
            'uptimeminutes': ut/60, #xbmc.getInfoLabel('System.Uptime'),
            'alivekey': time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
            'lastreboot': utstr,
            'lastupdatekey': 'SWARM Server Updated Client at: %s' % time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime(os.path.getctime(get_playdir()))),
            'certificate': open(os.path.join(get_playdir(), 'certificate.mvg')).read(),
        }
        #return template.format(**opts)
        return opts
    except:
        log.warning('can not generage report:\n' + get_traceback())

def send_report(scrfile=None):
    import databridge
    url='http://31.192.228.186/getdata.php'
#    url='http://requestb.in/rqwhwkrq'

    if not scrfile:
        scrfile = get_default_screenshot_file()

    data = generate_report()
    data["playdirid"]="2010-04-26-12-18-03"

    #uploading data
    result = databridge.send_data(url,
                data,
                scrfile);

    #if everything is ok the returned dictionary will be
    #  {'ok': True, 'error': None}
    if result and result.get('ok'):
        log.debug('send report result: %s' % result)
    else:
        log.warning('send report result: %s' % result)

def startup_clear_lock():
    # sometimes the lock need be unlocked when xbmc startup
    def unlock(lockname):
        try:
            lock = lockfile.LockFile(os.path.join(DATA_BASE_DIR, lockname))
            lock.break_lock()
            log.debug('startup unlock [%s] done.' % lockname)
        except lockfile.Error, e:
            log.debug('startup unlock [%s] failed: %s' % (lockname, e))
        except:
            log.debug('startup unlock [%s] exception, ignore.' % lockname)
    unlock('run_player')
    unlock('check_update')

def is_addon_active():
    return xbmc.getCondVisibility( "System.HasAddon(%s)" % ADDON_ID )

def check_scheduled_poweroff():
    if not plugin.get_setting('schedule_poweroff', bool, False):
#        log.debug('no scheduled poweroff')
        return
    wday_mapping = [6, 0, 1, 2, 3, 4, 5]
    def get_week_days(fromday, today):
        if fromday < 0 or today < 0:
            return []
        fromday = wday_mapping[fromday]
        today = wday_mapping[today]
        if fromday <= today:
            return range(fromday, today+1)
        return range(0, today+1) + range(fromday, 7)
    schedule_poweroff_rules = []

    def read_schedule_poweroff_rule(ruleid):
        for i in range(1, ruleid + 1):
            if not plugin.get_setting('schedule_poweroff%d' % ruleid, bool, False):
                return
        default_from = -1
        default_to = -1
        if ruleid == 0:
            default_from = 1
            default_to = 0 
        fromday = plugin.get_setting('schedule_poweroff_from_day%d' % ruleid, int, default_from)
        today = plugin.get_setting('schedule_poweroff_to_day%d' % ruleid, int, default_to)
        wdays = get_week_days(fromday, today)
        if wdays:
            h = plugin.get_setting('schedule_poweroff_hour%d' % ruleid, int, 23)
            m = plugin.get_setting('schedule_poweroff_min%d' % ruleid, int, 0)
            return (wdays, h, m)

    if plugin.get_setting('schedule_poweroff_custom', bool, False):
        for i in range(3):
            rule = read_schedule_poweroff_rule(i)
            if rule:
                schedule_poweroff_rules.append(rule)
    else:
        ruleid = 0
        h = plugin.get_setting('schedule_poweroff_hour%d' % ruleid, int, 23)
        m = plugin.get_setting('schedule_poweroff_min%d' % ruleid, int, 0)
        rule = (range(7), h, m)
        schedule_poweroff_rules.append(rule)

    lm = time.localtime()
    for wdays, h, m in schedule_poweroff_rules:
        if lm.tm_wday in wdays and h == lm.tm_hour and m == lm.tm_min:
            log.debug('scheduled poweroff at %s, current %s:%s:%s' % (schedule_poweroff_rules, wday_mapping.index(lm.tm_wday), lm.tm_hour, lm.tm_min))
            notify('scheduled power off at %s:%s' % (h, m))
            xbmc.executebuiltin("Powerdown")
            return True

def get_addon_version():
    return xbmcaddon.Addon(ADDON_ID).getAddonInfo('version')

def is_64bits():
    import struct
    return struct.calcsize("P") * 8 == 64
#log.debug('64bits: %s' % is_64bits())

def fix_pil_load():
    for p in sys.path:
        if p.endswith('site-packages'):
            eggs = [os.path.join(p, f) for f in os.listdir(p) if f.startswith('PIL') and f.endswith('.egg')]
            if eggs:
                egg = eggs[0]
                if egg not in sys.path:
                    sys.path.append(egg)
                    log.debug('fix pil path, sys.path now: %s' % sys.path)
                    return True
            break

class UpdateMonitor(xbmc.Monitor):
    update_method = None

    def __init__(self, *args, **kwargs):
        xbmc.Monitor.__init__(self)
        self.update_method = kwargs['update_method']

    def onSettingsChanged(self):
        self.update_method()

SCREENSHOT_BUILTIN_API = 0
SCREENSHOT_PYTHON_API = 1

class DMDSScheduler:
    def __init__(self):
        self.monitor = UpdateMonitor(update_method = self.settingsChanged)
        self.player_lock = lockfile.LockFile(os.path.join(DATA_BASE_DIR, 'run_player'))
        self.settingsChanged(False)
        self.last_screenshot_time = None
        self.last_report_time = None
        self.screenshotting = False
        self.screenshot_api = SCREENSHOT_BUILTIN_API
        self.screenshot_api = SCREENSHOT_PYTHON_API
        self.capture = xbmc.RenderCapture()
        self.capture_retry_times = 0
        self.loopcount = 0
        # if pil is broken, then we can not resize the screenshot to what we want.
        self.pil_is_broken = False
        try:
            import Image
            pixel = "\x01\x02\x03\x04"
            im = Image.fromstring("RGBA", (1, 1), pixel, "raw", "BGRA")
        except:
            try:
                from PIL import Image
                pixel = "\x01\x02\x03\x04"
                im = Image.fromstring("RGBA", (1, 1), pixel, "raw", "BGRA")
            except:
                self.pil_is_broken = True
        log.debug('pil_is_broken: %s' % self.pil_is_broken)
        plugin.set_setting('pil_is_broken', str(self.pil_is_broken).lower())

    def settingsChanged(self, logging=True):
        if logging:
            log.debug('DMDSScheduler().settingsChanged()')
        self.check_update_interval = plugin.get_setting('check_update_interval', int, -1)
        self.report_interval = plugin.get_setting('stat_report_interval', int, 600)
        self.ssdir = get_screenshot_dir()

    def run(self):
        log.debug('DMDSScheduler().run() begin')
        if self.check_update_interval >= 0:
            check_media_updates()
        last_check_time = time.time()

        # as an program/service both add-on, when uninstall the service is still running (xbmc bug)
        # but we need exit the loop here, and keep the service loop empty, then when the new add-on
        # installed, it will auto start running the run_on_startup again by the previous running serivce loop outside
        # for really re-init the add-on and service, disable and re-enable the add-on will do the work.
        while not xbmc.abortRequested and is_addon_active():
            xbmc.sleep(1000)
            self.loopcount += 1
            if self.loopcount % 30 == 0:
                check_scheduled_poweroff()
            if self.check_update_interval > 0 and time.time() - last_check_time >= self.check_update_interval:
                check_media_updates()
                last_check_time = time.time()
            self.check_scheduled_report()
        log.debug('DMDSScheduler().run() end')

    def check_scheduled_report(self):
        if self.screenshotting:
            self.check_screenshot_result()
        elif (self.last_report_time is None and self.loopcount % 15 == 14 or self.last_report_time is not None and time.time() - self.last_report_time >= self.report_interval) and self.player_lock.is_locked():
            log.debug('hit report time')
            if self.pil_is_broken:
                self.on_got_screenshot(False)
                self.last_report_time = time.time()
            elif self.screenshot_api == SCREENSHOT_PYTHON_API:
                log.debug('capturing')
                self.capture.capture(320, 180, xbmc.CAPTURE_FLAG_CONTINUOUS)
                self.screenshotting = True
            elif self.ssdir and plugin.get_setting('sync_screenshot', bool, True):
                self.screenshotting = True
                self.last_screenshot_time = int(time.time())
                xbmc.executebuiltin("TakeScreenshot(%s,sync)" % self.ssdir, True)
                #xbmc.executebuiltin("TakeScreenshot(%s)" % self.ssdir)
                self.check_screenshot_result()
            else:
                if not self.ssdir:
                    log.warning('no screenshot dir set in system debug settings.')
                self.on_got_screenshot(False)
                self.last_report_time = time.time()


    def check_screenshot_result(self):
        ret = None
        if self.screenshot_api == SCREENSHOT_PYTHON_API:
            self.capture.waitForCaptureStateChangeEvent(100)
            cstate = self.capture.getCaptureState()
            log.debug('capture state: %s' % cstate)
            if cstate == xbmc.CAPTURE_STATE_FAILED:
                self.capture_retry_times += 1
                if self.capture_retry_times < 5:
                    xbmc.sleep(1000)
                    log.debug('capturing retry %s' % self.capture_retry_times)
                    self.capture.capture(320, 180, xbmc.CAPTURE_FLAG_CONTINUOUS)
                    return
                self.capture_retry_times = 0
                ret = False
            elif cstate == xbmc.CAPTURE_STATE_DONE:
                try:
                    img = self.capture.getImage()
                    imgFormat = self.capture.getImageFormat()
                    log.debug('got captured image format: %s, raw size: %s' % (imgFormat, len(img)))
    
                    try:
                        import Image
                    except:
                         # the fix not work, since the c-runtime files in the egg won't load.
#                        if fix_pil_load():
#                            import Image
#                        else:
#                            from PIL import Image
                        from PIL import Image
                            
                    im = Image.fromstring('RGBA', (self.capture.getWidth(), self.capture.getHeight()), str(img), 'raw', imgFormat)
                    ssfile = os.path.join(DATA_BASE_DIR, 'screenshot.jpg')
                    im.save(ssfile)
                    del img
                    ret = ssfile
                except ImportError:
                    log.debug(str(sys.path))
                    log.warning('can not load PIL module:\n' + get_traceback())
                    ret = False
                except:
                    log.debug(str(sys.path))
                    log.warning('can not save screenshot:\n' + get_traceback())
                    ret = ''
        else:
            if not self.ssdir:
                ret = False
            while not ret:
                try:
                    ssfile = max([os.path.join(self.ssdir, f) for f in os.listdir(self.ssdir) if f.startswith('screenshot')], key=os.path.getmtime)
                except ValueError:
                    log.debug('no screenshot file found yet')
                    break
                mt = os.path.getmtime(ssfile)
                log.debug('mt: %s, last: %s' % (mt, self.last_screenshot_time))
                if mt >= self.last_screenshot_time:
                    fsize = os.path.getsize(ssfile)
                    if fsize == 0:
                        log.debug('got empty screenshot file: %s, delay: %s' % (ssfile, mt - self.last_screenshot_time))
                        log.debug('save setting that this xbmc build does not support sync screenshot')
                        plugin.set_setting('sync_screenshot', 'false')
                        ret = ''
                        break
                    log.debug('got screenshot file: %s, filesize: %s, delay: %s' % (ssfile, fsize, mt - self.last_screenshot_time))
                    if mt < self.last_screenshot_time + 20:
                        # it should be saved in 20 seconds?
                        # TODO: handle too small screenshot (empty/black screen)
                        ret = ssfile
                        break
                else:
                    log.debug('no new screenshot file, current newest: %s, delay: %s' % (ssfile, mt - self.last_screenshot_time))
                break
        if ret is not None:
            self.screenshotting = False
            self.on_got_screenshot(ret)
            self.last_report_time = time.time()
        return ret
            
    def on_got_screenshot(self, ssfile):
        try:
            send_report(ssfile)
        except:
            log.warning('can not send report:\n' + get_traceback())
#        if ssfile:
#            try:
#                os.remove(ssfile)
#            except:
#                pass


@plugin.route('/run_on_startup')
def run_on_startup():
    log.debug('run_on_startup start running, service version: %s, code version: %s' % (plugin.addon.getAddonInfo('version'), get_addon_version()))
#    following code now running in the service.py only for the first time be called.
#    startup_clear_lock()
#    check_ask_set_skin_background()

    th = None
    if runonstartup:
        xbmc.executebuiltin('RunPlugin(plugin://plugin.program.dmdsplayer/run_dmds_player)')

    DMDSScheduler().run()

    log.debug('run_on_startup exited.')


@plugin.route('/run_dmds_player')
def run_dmds_player():
    run_dmds_player_nolock()

@lock_and_call_else_fail('run_player')
def run_dmds_player_nolock(nogui = nogui):
    def notify(msg, nogui = nogui):
        if nogui:
            log.info(msg)
        else:
            plugin.notify(msg)

    playdir = get_playdir()
    if not os.path.isdir(playdir):
        notify('non-existed playdir: %s' % playdir)
        return
    from run import pre_init, run
    notify('starting dmds player...')
    pre_init(playdir)
    run()
    notify('dmds player stopped.')

if __name__ == '__main__':
    pass
